//
//  ImageViewController.m
//  OtakuWorld
//
//  Created by iOS Two on 14-9-28.
//  Copyright (c) 2014年 iOS Two. All rights reserved.
//

#import "ImageViewController.h"
#import "UIImageView+MJWebCache.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"

@interface ImageViewController ()

@end

@implementation ImageViewController
-(void)viewWillAppear:(BOOL)animated {
    [MobClick beginLogPageView:@"ImageViewController"];
}
-(void)viewWillDisappear:(BOOL)animated {
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate.leveyTabBarController hidesTabBar:NO animated:YES];
    [MobClick endLogPageView:@"ImageViewController"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (version >= 7) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"112_01"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    } else {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"112_01"] forBarMetrics:UIBarMetricsDefault];
    }
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate.leveyTabBarController hidesTabBar:YES animated:YES];
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"backAR"] style:UIBarButtonItemStyleDone target:self action:@selector(buttonClick)];
    [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:0.99 green:0.62 blue:0.27 alpha:1]];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -15;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, back, nil];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
    label.text = _titleLabel;
    label.textColor = [UIColor colorWithRed:0.99 green:0.62 blue:0.27 alpha:1];
    label.font = [UIFont fontWithName:@"STXIHEI" size:20];
    [label sizeToFit];
    self.navigationItem.titleView = label;
    
    
    _i = 12;
    _j = 0;
    _url = [NSURL URLWithString:[NSString stringWithFormat:@"http://animemaster.sinaapp.com/api_photo.php?aid=%@&start=0&count=12",_aid]];
    _urlArray = [[NSMutableArray alloc]init];
    _widthArray = [[NSMutableArray alloc]init];
    _heightArray = [[NSMutableArray alloc]init];
    _imageArray = [[NSMutableArray alloc]init];
    [self creatController];
    [self getData];
    // Do any additional setup after loading the view.
}
-(void)buttonClick {
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate.leveyTabBarController hidesTabBar:NO animated:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatController {
    UIView *back = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 64)];
    [self.view addSubview:back];
    
    _waterView = [[ZBWaterView alloc]initWithFrame:CGRectMake(0, 0, kwidth, kHeight - 64)];
    _waterView.waterDataSource = self;
    _waterView.waterDelegate = self;
    _waterView.isDataEnd = NO;
    [self.view addSubview:_waterView];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)getData {
//    [self showIndeterminateProgress];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc]initWithURL:_url];
    request.delegate = self;
    request.username = @"info";
    [request startSynchronous];
}
-(void)requestFinished:(ASIHTTPRequest *)request {
    SBJsonParser *jsonP = [[SBJsonParser alloc]init];
    if ([request.username isEqualToString:@"info"]) {
        NSArray *array =[jsonP objectWithData:[request responseData]];
        if (array.count < 12) {
            _waterView.isDataEnd = YES;
        }
        for (int i = 0; i < array.count; i++) {
            [_heightArray addObject:[[array objectAtIndex:i] objectForKey:@"height"]];
            [_widthArray addObject:[[array objectAtIndex:i] objectForKey:@"width"]];
            [_urlArray addObject:[[array objectAtIndex:i] objectForKey:@"path_qiniu"]];
            
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 145, [[[array objectAtIndex:i] objectForKey:@"height"] floatValue] / ([[[array objectAtIndex:i] objectForKey:@"width"] floatValue] / 145))];
            [image setImageURLStr:[NSString stringWithFormat:@"http://acgwallpaper.qiniudn.com/%@-sthumb",[[array objectAtIndex:i]objectForKey:@"path_qiniu"]] placeholder:[UIImage imageNamed:@"error"]];
            image.tag = _j;
            image.userInteractionEnabled = YES;
            [image addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
            [_imageArray addObject:image];
            _j = _j + 1;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_waterView endLoadMore];
            [_waterView reloadData];
        });
    }
//    [HUD hide:YES];
}
-(void)requestFailed:(ASIHTTPRequest *)request {
    NSLog(@"请求失败");
}
-(void)buttonClick:(UITapGestureRecognizer *)sender {
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:_imageArray.count];
    for (int i = 0; i < _imageArray.count; i++) {
        NSString *string = [NSString stringWithFormat:@"http://acgwallpaper.qiniudn.com/%@",[_urlArray objectAtIndex:i]];
        // 替换为中等尺寸图片
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.url = [NSURL URLWithString:string]; // 图片路径
        photo.srcImageView = _imageArray[i]; // 来源于哪个UIImageView
        [photos addObject:photo];
    }
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = sender.view.tag; // 弹出相册时显示的第一张图片是？
    browser.photos = photos; // 设置所有的图片
    //    browser.imgId = _imgIdArray;
    [browser show];
}
- (NSInteger)numberOfFlowViewInWaterView:(ZBWaterView *)waterView {
    return _imageArray.count;
}

- (CustomWaterInfo *)infoOfWaterView:(ZBWaterView*)waterView {
    CustomWaterInfo *info = [[CustomWaterInfo alloc] init];
    info.topMargin = 0;
    info.leftMargin = 10;
    info.bottomMargin = 0;
    info.rightMargin = 10;
    info.horizonPadding = 10;
    info.veticalPadding = 10;
    info.numOfColumn = 2;
    return info;
}

- (ZBFlowView *)waterView:(ZBWaterView *)waterView flowViewAtIndex:(NSInteger)index {
    ZBFlowView *flowView = [waterView dequeueReusableCellWithIdentifier:@"cell"];
    if (flowView == nil) {
        flowView = [[ZBFlowView alloc] initWithFrame:CGRectZero];
        flowView.reuseIdentifier = @"cell";
    } else {
        for (UIView *view in [flowView subviews]) {
            [view removeFromSuperview];
        }
    }
    flowView.index = index;
    [flowView addSubview:[_imageArray objectAtIndex:index]];
    
    return flowView;
}
- (void)needLoadMoreByWaterView:(ZBWaterView *)waterView {
    _url = [NSURL URLWithString:[NSString stringWithFormat:@"http://animemaster.sinaapp.com/api_photo.php?aid=%@&start=%d&count=12",_aid,_i]];
    _i = _i + 12;
    [self getData];
}
- (CGFloat)waterView:(ZBWaterView *)waterView heightOfFlowViewAtIndex:(NSInteger)index {
    CGFloat height = [[_heightArray objectAtIndex:index] floatValue] / ([[_widthArray objectAtIndex:index] floatValue] / 145);
    return height;
}
- (void)waterView:(ZBWaterView *)waterView didSelectAtIndex:(NSInteger)index
{
    NSLog(@"didSelectAtIndex%d",index);
}
@end
